package com.bm.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bm.Do.owner.*;
import com.bm.Result.CodeEnum;
import com.bm.Vo.owner.OwnerApplyDetailVo;
import com.bm.Vo.owner.OwnerApplyReplyVo;
import com.bm.Vo.owner.OwnerApproveVo;
import com.bm.Vo.owner.OwnerDetailVo;
import com.bm.constant.Constants;
import com.bm.exception.BmException;
import com.bm.mapper.EjyyOwnerDetailLogMapper;
import com.bm.mapper.EjyyUserBuildingMapper;
import com.bm.mapper.EjyyWechatMpUserMapper;
import com.bm.model.EjyyOwnerApply;
import com.bm.model.EjyyOwnerDetailLog;
import com.bm.model.EjyyUserBuilding;
import com.bm.query.Common.InfoQuery;
import com.bm.query.owner.OwnerApplyListQuery;
import com.bm.query.owner.OwnerApplyReplyQuery;
import com.bm.query.owner.OwnerApproveQuery;
import com.bm.query.owner.OwnerListQuery;
import com.bm.service.EjyyOwnerApplyService;
import com.bm.mapper.EjyyOwnerApplyMapper;
import com.bm.util.AuthContextUtil;
import com.bm.util.CommunityUtil;
import com.bm.util.DateUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.bm.constant.Constants.AUTHENTICTED_BY_PROPERTY_COMPANY;
import static com.bm.constant.Constants.EXPRIE_Time;

/**
 *
 */
@Service
public class EjyyOwnerApplyServiceImpl extends ServiceImpl<EjyyOwnerApplyMapper, EjyyOwnerApply>
        implements EjyyOwnerApplyService {

    @Autowired
    private EjyyOwnerApplyMapper ownerApplyMapper;

    @Autowired
    private EjyyUserBuildingMapper userBuildingMapper;

    @Autowired
    private EjyyOwnerDetailLogMapper ownerDetailLogMapper;

    @Autowired
    private EjyyWechatMpUserMapper wechatMpUserMapper;

    /**
     * 分页查询
     *
     * @param ownerApplyListQuery
     * @return
     */
    @Override
    public PageInfo<OwnerApplyListDo> ownerApplyList(OwnerApplyListQuery ownerApplyListQuery) {
        //调用mapper查询
        List<OwnerApplyListDo> list = ownerApplyMapper.selectPageList(ownerApplyListQuery);
        //放入分页参数
        PageHelper.startPage(ownerApplyListQuery.getPageNum(), ownerApplyListQuery.getPageSize());
        //创建分页对象将数据放入
        PageInfo<OwnerApplyListDo> listDoPageInfo = new PageInfo<>(list);
        return listDoPageInfo;
    }


    /**
     * 申请答复
     *
     * @param ownerApplyReplyQuery
     * @return
     */
    @Override
    public OwnerApplyReplyVo OwnerApplyReply(OwnerApplyReplyQuery ownerApplyReplyQuery) {
        LambdaQueryWrapper<EjyyOwnerApply> lqw = new LambdaQueryWrapper<>();
        List<Long> ids = new ArrayList<>();
        lqw.eq(EjyyOwnerApply::getId, ownerApplyReplyQuery.getId());
        lqw.eq(EjyyOwnerApply::getCommunityId, ownerApplyReplyQuery.getCommunityId());
        EjyyOwnerApply detail = ownerApplyMapper.selectOne(lqw);
        if (ObjectUtils.isEmpty(detail) || detail.getReplied() == true) {
            throw new BmException(CodeEnum.STATUS_ERROR);
        }

        if (ownerApplyReplyQuery.getSuccess() && ownerApplyReplyQuery.getBuildingIds().size() <= 0) {
            throw new BmException(CodeEnum.SYSTEM_PARAMETER_IS_EMPTY);
        }

        if (ownerApplyReplyQuery.getSuccess()) {
            List<Long> buildingsInfo = ownerApplyMapper.selectIdOnOwner(ownerApplyReplyQuery.getBuildingIds());
            if (buildingsInfo.size() == 0) {
                throw new BmException(CodeEnum.NOT_FOUND_BINDING_BUILDING);
            }

            EjyyUserBuilding bindingDataDo = new EjyyUserBuilding();
            //遍历id封装对象
            for (Long id : buildingsInfo) {
                bindingDataDo.setBuildingId(id);
                bindingDataDo.setWechatMpUserId(detail.getWechatMpUserId());
                bindingDataDo.setAuthenticated(Boolean.TRUE);
                bindingDataDo.setAuthenticatedType(AUTHENTICTED_BY_PROPERTY_COMPANY);
                bindingDataDo.setAuthenticatedUserId(Long.parseLong(AuthContextUtil.get().getId() + ""));
                bindingDataDo.setCreatedAt(DateUtils.dateConversion());
                ids.add(id);
            }
            //新增答复
            userBuildingMapper.insert(bindingDataDo);
        }
        //创建答复对象
        EjyyOwnerApply ownerApply = new EjyyOwnerApply();
        //封装最新的答复信息
        ownerApply.setReplyContent(ownerApplyReplyQuery.getReplyContent());
        ownerApply.setReplied(true);
        ownerApply.setContent(JSONUtil.toJsonStr(ids));
        ownerApply.setRepliedBy(Long.parseLong(AuthContextUtil.get().getId() + ""));
        ownerApply.setSuccess(ownerApplyReplyQuery.getSuccess());
        //修改数据库中的答复信息
        int count = ownerApplyMapper.update(ownerApply, lqw);
        if (ownerApplyReplyQuery.getSuccess() && detail.getSubscribed()) {
            //小程序端的内容 查询数据库 推送小程序
        }
        //数据库查询绑定的信息
        List<OwnerApplyReplyDo> OwnerApplyReplyDo = ownerApplyMapper.selectBuildings(ownerApply.getCommunityId(), detail.getWechatMpUserId(), ids);
        //创建返回对象
        OwnerApplyReplyVo ownerApplyReplyVo = new OwnerApplyReplyVo();
        //放入信息
        ownerApplyReplyVo.setBuildings(OwnerApplyReplyDo);
        //放入时间
        ownerApplyReplyVo.setRepliedAt(DateUtils.dateConversion());
        return ownerApplyReplyVo;
    }


    /**
     * 批准同意
     *
     * @param ownerApproveQuery
     * @return
     */
    @Override
    public OwnerApproveVo ownerApprove(OwnerApproveQuery ownerApproveQuery) {
        List<Long> ids = ownerApplyMapper.selectInfoByIds(ownerApproveQuery);
        if (ids.size() != ownerApproveQuery.getBuildingIds().size()) {
            return null;
        }
        String encrypt = CommunityUtil.encrypt(ownerApproveQuery.getBuildingIds(), AUTHENTICTED_BY_PROPERTY_COMPANY, AuthContextUtil.get().getId());
        //封装返回对象
        OwnerApproveVo ownerApproveVo = new OwnerApproveVo();
        //放入加密后的数据
        ownerApproveVo.setRes(encrypt);
        //放入过期时间7天
        ownerApproveVo.setExpire(Integer.valueOf((DateUtils.dateConversion()+EXPRIE_Time) + ""));
        return ownerApproveVo;
    }

    /**
     * 详情
     * @param infoQuery
     * @return
     */
    @Override
    @Transactional
    public OwnerDetailVo ownerDetail(InfoQuery infoQuery) {
        OwnerInfoDo info = ownerApplyMapper.selectInfo(infoQuery.getId());
        if(ObjectUtils.isEmpty(info)){
            return null;
        }
        List<OwnerBuildingsDo> ownerBuildingsDo = ownerApplyMapper.selectbuildings(infoQuery);
        if(ownerBuildingsDo.size() == 0){
            //根据条件查询
            LambdaQueryWrapper<EjyyOwnerApply> lqw = new LambdaQueryWrapper<>();
            //构建条件
            lqw.eq(EjyyOwnerApply::getCommunityId,infoQuery.getCommunityId());
            lqw.eq(EjyyOwnerApply::getWechatMpUserId,infoQuery.getId());
            lqw.eq(EjyyOwnerApply::getSuccess,false);
            EjyyOwnerApply ejyyOwnerApply = ownerApplyMapper.selectOne(lqw);
            if(ObjectUtils.isEmpty(ejyyOwnerApply)){
                return null;
            }
        }
        List<Long> buildings = ownerBuildingsDo.stream().map((item) -> {
            return item.getBuildingId();
        }).collect(Collectors.toList());
        List<OwnerCarsDo> ownerCarsDo = ownerApplyMapper.selectUserCars(infoQuery.getId(),buildings);

        EjyyOwnerDetailLog OwnerDetailLog = new EjyyOwnerDetailLog();
        OwnerDetailLog.setWechatMpUserId(infoQuery.getId());
        OwnerDetailLog.setPropertyCompanyUserId(Long.parseLong(AuthContextUtil.get().getId()+""));
        OwnerDetailLog.setCreatedAt(DateUtils.dateConversion());

        //调用mapper新增
        ownerDetailLogMapper.insert(OwnerDetailLog);
        //构建返回对象
        OwnerDetailVo ownerDetailVo = new OwnerDetailVo();
        //构建数据
        ownerDetailVo.setBuildings(ownerBuildingsDo);
        ownerDetailVo.setCars(ownerCarsDo);
        ownerDetailVo.setInfo(info);

        return ownerDetailVo;
    }


    /**
     * 查询所有人气信息
     * @param ownerListQuery
     * @return
     */
    @Override
    public PageInfo<OwnerListDo> ownerList(OwnerListQuery ownerListQuery) {
        PageHelper.startPage(ownerListQuery.getPageNum(),ownerListQuery.getPageSize());
        //调用mapper查询
        List<OwnerListDo> ownerListDo = wechatMpUserMapper.selectOwnerListById(ownerListQuery);

        PageInfo<OwnerListDo> info = new PageInfo<>(ownerListDo);

        return info;
    }

    /**
     * 查询申请详情
     * @param infoQuery
     * @return
     */
    @Override
    public OwnerApplyDetailVo ownerApplyDetail(InfoQuery infoQuery) {
        OwnerApplyDetailInfoDo info = ownerApplyMapper.selectOwnerApplyInfo(infoQuery);
        if(ObjectUtils.isEmpty(info)){
            return null;
        }
        List<OwnerApplyDetailBuildingDo> buildings = ownerApplyMapper.selectOwnerApplyBuildings(info.getWechatMpUserId(),info.getContent(),infoQuery.getCommunityId());
        //清除敏感数据
        info.setContent(null);

        //构建返回对象
        OwnerApplyDetailVo ownerApplyDetailVo = new OwnerApplyDetailVo();
        ownerApplyDetailVo.setInfo(info);
        ownerApplyDetailVo.setBuildings(buildings);

        return ownerApplyDetailVo;
    }
}
